class GameBoard {
    constructor(rows = 20, cols = 10) {
        this.rows = rows;
        this.cols = cols;
        this.grid = Array(rows).fill().map(() => Array(cols).fill(null));
        this.linesCleared = 0;
    }

    // 检查位置是否有效（在边界内且没有方块）
    isValidPosition(block) {
        const cells = block.getCells();

        for (const cell of cells) {
            // 检查边界
            if (cell.x < 0 || cell.x >= this.cols || cell.y < 0 || cell.y >= this.rows) {
                return false;
            }

            // 检查碰撞
            if (cell.y >= 0 && this.grid[cell.y][cell.x] !== null) {
                return false;
            }
        }

        return true;
    }

    // 将方块固定到网格中
    placeBlock(block) {
        const cells = block.getCells();

        for (const cell of cells) {
            if (cell.y >= 0 && cell.y < this.rows) {
                this.grid[cell.y][cell.x] = block.color;
            }
        }

        return this.clearLines();
    }

    // 清除已填满的行
    clearLines() {
        let linesCleared = 0;

        for (let row = this.rows - 1; row >= 0; row--) {
            if (this.isLineFull(row)) {
                this.clearLine(row);
                linesCleared++;
                row++; // 重新检查当前行，因为上面的行已经下移
            }
        }

        this.linesCleared += linesCleared;
        return linesCleared;
    }

    // 检查一行是否已填满
    isLineFull(row) {
        return this.grid[row].every(cell => cell !== null);
    }

    // 清除一行并使上面的行下移
    clearLine(row) {
        // 删除该行
        this.grid.splice(row, 1);
        // 在顶部添加新的空行
        this.grid.unshift(Array(this.cols).fill(null));
    }

    // 重置游戏板
    reset() {
        this.grid = Array(this.rows).fill().map(() => Array(this.cols).fill(null));
        this.linesCleared = 0;
    }
}